<?php
/**
 * Created by PhpStorm.
 * User: linlin
 * Date: 2017/11/13
 * Time: 9:46
 */

namespace app\Modules\Api\models;
use app\models\Sign as BaseModel;

class Sign extends BaseModel
{
    public function fields()
    {
        $fields = parent::fields();
        $strvalfields = [
            'signid',
            'user_id',
            'take_money',
            'continuity',
        ];

        foreach($strvalfields as $strvalfield){
            $fields[$strvalfield] = function() use ($strvalfield){
                return strval($this->$strvalfield);
            };
        }
        $dateFields = ['created_at','updated_at'];
        foreach($dateFields as $dateField){
            $fields[$dateField] = function() use($dateField){
                return Date('Y-m-d G:i:s',$this->$dateField);
            };
        }
        unset($fields['signid']);
        unset($fields['continuity']);
        unset($fields['updated_at']);
        return $fields;
    }

    public static function getContinuity($user_id)
    {
        /** @var  $top self*/
        $top = self::find()->where(['user_id'=>$user_id])->orderBy(['created_at'=>SORT_DESC])->one();
        if(!$top)//没有签到记录
            return 0;
        $yesterday = Date('Y-m-d',strtotime('Yesterday'));
        $now = Date('Y-m-d');
        $created_at = Date('Y-m-d',$top->created_at);
        if($created_at>=$now)//签到过
            return false;
        else if($created_at=$yesterday)//昨天签的到，今天可以连续签
            return $top->continuity;
        else//断签
            return 0;
    }

    public static function getTakeMoney($continuity)
    {
        if($continuity=== false)
            return 0;

        $continuity += 1;
        $take_money = 0;

        if($continuity<5){
            $take_money = 3;
        }else if($continuity>=5&&$continuity<15){
            $take_money = 5;
        }else if($continuity>=15){
            $take_money = 7;
        }
        return $take_money;
    }
}